<template>
  <div>
    <Card>
      <Tables ref="tables" searchable search-place="top" :loading="listLoading" :columns="columns" v-model="list">
        <template slot="handleButton">
          <Button v-if="tenantManager_btn_add" type="primary" @click="handleAdd"><Icon type="md-add" />新增</Button>
        </template>
        <template slot="searchButton">
          <div style="float:right">
            <Input placeholder="租户名称" class="search-input" v-model="listQuery.name">
            <Button @click="getList" slot="append" type="info" icon="ios-search"></Button>
            </Input>
          </div>
        </template>
        <template slot="action" slot-scope="scope">
          <Divider type="vertical" />
          <Button v-if="tenantManager_btn_user" type="primary" size="small" @click="handleUser(scope.row)">设置管理员</Button>
          <Poptip confirm title="确定冻结用户?" transfer @on-ok="handleFrozen(scope.row)">
            <Button v-if="tenantManager_btn_frozen" type="warning" size="small">冻结</Button>
          </Poptip>
          <Button v-if="tenantManager_btn_edit" type="primary" size="small" @click="handleEdit(scope.row)">编辑</Button>
          <Button v-if="tenantManager_btn_edit" type="primary" size="small" @click="handleDel(scope.row)">删除</Button>
        </template>
      </Tables>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: left;">
          <Page v-show="!listLoading" :total="total" :page-size-opts="[50,100,500,1000]" :current="listQuery.page" show-total show-sizer :page-size="listQuery.limit" @on-change="handleCurrentChange" @on-page-size-change="handleSizeChange"></Page>
        </div>
      </div>
      <Modal :title="textMap[dialogStatus]" v-model="dialogFormVisible" :mask-closable='false' :width="500">
        <Form ref="form" :model="form" :label-width="100" :rules="rules">
          <FormItem label="编码" prop="code">
            <Input v-model="form.code"/>
          </FormItem>
          <FormItem label="租户名称" prop="name">
            <Input v-model="form.name" placeholder="请输入租户名称"/>
          </FormItem>
          <FormItem label="描述" prop="description">
            <Input v-model="form.description" placeholder="请输入描述"/>
          </FormItem>
          <FormItem label="是否超级租户" prop="isSuperTenant">
              <i-switch :value="form.isSuperTenant" :true-value="'1'" :false-value="'0'"/>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="cancel('form')">取消</Button>
          <Button type="primary" v-if="dialogStatus=='create'" @click="create('form')">确 定</Button>
          <Button type="primary" v-else @click="update('form')">确 定</Button>
        </div>
      </Modal>
      <Modal title="设置管理员" v-model="dialogUserVisible" :mask-closable='false' :width="500" @on-ok="confirmUser" @on-cancel="cancelUser">
        <Select ref="userSelect" v-model="currentUser" placeholder="请输入用户名" :loading="loading" filterable remote :remote-method="remoteMethod">
          <Option v-for="(item, index) in  users" :label="item.name" :value="item.id" :key="index">{{item.name}}</Option>
        </Select>
      </Modal>
    </Card>
  </div>
</template>
<script>
import Tables from '_c/tables'
import { mapGetters } from 'vuex'
import {
  page,
  addObj,
  getObj,
  delObj,
  putObj,
  updateUser,
  getOwner
} from '@/api/admin/tenant/index'
import {
  page as pageUser
} from '@/api/admin/user/index'
export default {
  name: 'tenant',
  components: {
    Tables
  },
  data () {
    return {
      tenantManager_btn_add: false,
      tenantManager_btn_frozen: false,
      tenantManager_btn_edit: false,
      tenantManager_btn_del: false,
      tenantManager_btn_user: false,
      listLoading: false,
      total: 0,
      list: [],
      users: [],
      loading: false,
      currentId: undefined,
      currentUser: undefined,
      remote: false,
      listQuery: {
        page: 1,
        limit: 50,
        name: undefined
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      form: {
        code: undefined,
        name: undefined,
        description: undefined,
        isSuperTenant: '0'
      },
      rules: {
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入最后更新时间',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      dialogFormVisible: false,
      dialogUserVisible: false,
      dialogStatus: '',
      columns: [
        { title: '租户名称', key: 'name' },
        { title: '是否超级租户',
          key: 'isSuperTenant',
          render: (h, params) => {
            let content = '普通租户'
            let color = 'primary'
            if (params.row.isSuperTenant === '1') {
              content = '超级租户'
              color = 'red'
            }
            return h('Tag', { props: { color: color } }, content)
          }
        },
        { title: '描述', key: 'description' },
        { title: '创建时间', key: 'crtTime' },
        { title: '更新时间', key: 'updTime' },
        { title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.tables.$scopedSlots.action(params)
            )
          }
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  created () {
    this.tenantManager_btn_add = this.elements['tenantManager:btn_add']
    this.tenantManager_btn_edit = this.elements['tenantManager:btn_edit']
    this.tenantManager_btn_del = this.elements['tenantManager:btn_del']
    this.tenantManager_btn_user = this.elements['tenantManager:btn_user']
  },
  methods: {
    create (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form)
            .then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$Notice.success({
                title: '成功',
                desc: '创建成功'
              })
            })
        } else {
          return false
        }
      })
    },
    update (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$Notice.success({
              title: '成功',
              desc: '修改成功'
            })
          })
        } else {
          return false
        }
      })
    },
    cancel (formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.getList()
    },
    remoteMethod (query) {
      console.log(query)
      if (query !== '') {
        this.loading = true
        pageUser({ name: query, username: query }).then(response => {
          this.loading = false
          this.users = response.data.rows
        })
      } else {
        this.users = []
      }
    },
    cancelUser () {
      this.dialogUserVisible = false
    },
    confirmUser () {
      updateUser(this.currentId, { userId: this.currentUser }).then(() => {
        this.$Notice.success({
          title: '成功',
          desc: '设置管理员成功'
        })
        this.dialogUserVisible = false
      })
    },
    getList () {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        })
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    handleAdd () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUser (row) {
      this.users = []
      this.currentId = row.id
      this.dialogUserVisible = true
      this.currentUser = undefined
      // 通过 查询API找到使用该属性可避免在赋值时触发远程查询 导致下拉框为空的BUG
      this.$refs.userSelect.preventRemoteCall = false
      getOwner(row.id).then(response => {
        const user = response.data
        this.users.push(user)
        this.currentUser = row.owner
        this.$refs.userSelect.preventRemoteCall = true
      })
    },
    handleDel (row) {
      delObj(row.id)
        .then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '删除成功'
          })
          this.getList()
        })
    },
    handleEdit (row) {
      getObj(row.id)
        .then(response => {
          this.form = response.data
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
    },
    handleFrozen () {

    },
    resetTemp () {
      this.form = {
        code: undefined,
        name: undefined,
        description: undefined,
        isSuperTenant: '0'
      }
    }
  }
}
</script>
